#include "Grid.h"
#include "Chunk.h"

Grid::Grid()
{
	chunks.resize(5); 
	for(auto &chunk_y : chunks) 
	{ 
		chunk_y.resize(5); 
	} 
}

Grid::~Grid()
{
}

ChunkPtr &Grid::getChunk(Vec2i pos) 
{
	pos.clamp(-2, 2); //Clamp within bounds
	pos += 2; //transform to unsigned int
	return chunks[pos.x()][pos.y()]; 
}

ChunkPtr Grid::getChunkWithinBounds(Vec2i world_pos)
{
	for(int x = 0; x < chunks.size(); x++)
	{
		for(int y = 0; y < chunks[x].size(); y++)
		{
			if(chunks[x][y])
			{
				auto &chunk_LB = chunks[x][y]->getLowerBounds();
				auto &chunk_UB = chunks[x][y]->getUpperBounds();
				if(chunk_LB <= world_pos && chunk_UB > world_pos)
					return chunks[x][y];
			}
		}
	}
	return nullptr;
}

void Grid::move(Vec2i dir)
{
	dir.clamp(-1,1); //Only allowed to move 1 unit in any direction
	//dir += 2; //transform to unsigned int

	std::vector<std::vector<ChunkPtr>> temp_chunks;
	temp_chunks.resize(5);
	for(auto &temp_chunks_y : temp_chunks)
		temp_chunks_y.resize(5);

	for(int temp_x = 0; temp_x < temp_chunks.size(); temp_x++)
	{
		for(int temp_y = 0; temp_y < temp_chunks[temp_x].size(); temp_y++)
		{
			int x = temp_x + dir.x();
			int y = temp_y + dir.y();
			if(	x < 0 || x >= chunks.size() || 
				y < 0 || y >= chunks[temp_x].size())
			{
				temp_chunks[temp_x][temp_y] = nullptr;
			}
			else
			{
				temp_chunks[temp_x][temp_y] = std::move(chunks[x][y]);
			}
		}
	}
	for(int x = 0; x < temp_chunks.size(); x++)
	{
		for(int y = 0; y < temp_chunks[x].size(); y++)
		{
			chunks[x][y] = std::move(temp_chunks[x][y]);
		}
	}
}
